package com.baihui.taobao.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

import com.baihui.crm.BaihuiSession;
import com.baihui.crm.DES;
import com.baihui.crm.TicketMgr;
import com.baihui.crm.export.ExportContacts;
import com.baihui.crm.export.ExportOrder;
import com.baihui.crm.export.ExportProduct;
import com.baihui.crm.util.BaihuiException;
import com.baihui.taobao.AppConstants;
import com.baihui.taobao.authorize.TaoBaoCallBackUrlMgt;
import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.authorize.TopParameter;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.TPSessionDAO;
import com.baihui.taobao.quartz.jobs.BuyerImportJob;
import com.baihui.taobao.quartz.jobs.InvImportJob;
import com.baihui.taobao.quartz.jobs.OrderImportJob;
import com.baihui.taobao.quartz.jobs.ProductImportJob;
import com.baihui.taobao.transition.ImportItemCatDataCase;
import com.baihui.taobao.transition.ImportProductDataCase;
import com.baihui.taobao.transition.OrderCase;
import com.baihui.taobao.transition.UserCase;
import com.baihui.taobao.util.Util;
import com.taobao.api.domain.User;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 11-12-25 Time: 下午9:12
 */
public class TaobaoSessionServlet extends HttpServlet {

	static Logger logger = Logger.getLogger(TaobaoSessionServlet.class);

	public final static String[] actions = new String[] { "init",
			"importItemCatData", "viewImportItemCatDataProgress",
			"importProductData", "viewImportProductDataProgress",
			"importOrderData", "viewImportOrderDataProgress", "association",
			"viewprogress", "updateSchduleTask", "reschduleTask", "viewLog",
			"updatePassword", "deleteSchdulerTask", "stopSchdulerTask",
			"taobaouser" };

	private SchedulerFactory schedulerFactory = new StdSchedulerFactory();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		handleRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		handleRequest(req, resp);
	}

	/**
	 * .第一次通过淘宝进入：授权，同步用户，导入数据. 注意事项: 回调地址为我们提供的一个Servlet，需要部署在百会CRM中.
	 * 百会提供同步用户的API 淘宝的参数中不会附带授权用户的密码，因此同步到百会中的用户自动给予初始密码，登录百会后提示用户激活并修改密码。
	 * 同时会将用户的其他信息，比如Session和Session过期时长等信息保存在新建的表中。
	 * 淘宝昵称有可能是中文，此时会将淘宝用户的UserID,Email,Nickname等都传递给百会，百会决定是否需要支持中文名称来进行登录。
	 * 
	 * @param req
	 * @param resp
	 */
	private void handleRequest(HttpServletRequest req, HttpServletResponse resp) {
		try {

			// action校验
			String action = req.getParameter(AppConstants.ACTION);
			if (action == null || action.equals("")) {
				writeResponse(req, resp, null, "无效的请求，操作为空！");
				return;
			}

			if (!validActions(action)) {
				writeResponse(req, resp, null, "无效的请求，无法识别的操作：" + action + "！");
				return;
			}

			// // 安全性校验, 暂时注释掉
			// if (!validateSecurity(req, resp, action)) {
			// System.out.println();
			// writeResponse(req, resp, null, "无效的请求，无法通过安全校验！");
			// return;
			// }

			// 启动调度任务
			if (action.equals("reSchedulerTask")) {
				startSchedulerTask(req, resp);
			}

			// 根据action进行导向
			if (action.equals("init")) {
				initAuthorize(req, resp);
			}

			// 导入类目数据
			if (action.equals("importItemCatData")) {
				importItemCatData(req, resp);
			}

			// 导入类目进度
			if (action.equals("viewImportItemCatDataProgress")) {
				viewItemCatImportProgress(req, resp);
			}

			// 导入商品数据
			if (action.equals("importProductData")) {
				importProductData(req, resp);
			}

			// 导入类目进度
			if (action.equals("viewImportProductDataProgress")) {
				viewProductImportProgress(req, resp);
			}

			// 导入订单数据
			if (action.equals("importOrderData")) {
				importOrderData(req, resp);
			}

			// 导入订单进度
			if (action.equals("viewImportOrderDataProgress")) {
				viewOrderImportProgress(req, resp);
			}

			// 修改密码
			if (action.equals("updatePassword")) {
				updatePassword(req, resp);
			}

			if (action.equals("association")) {
				association(req, resp);
			}

			if (action.equals("viewprogress")) {
				viewprogress(req, resp);
			}

			if (action.equals("updateSchduleTask")) {
				updateSchduleTask(req, resp);
			}

			if (action.equals("deleteSchdulerTask")) {
				deleteSchduleTask(req, resp);
			}

			if (action.equals("stopSchdulerTask")) {
				stopSchduleTask(req, resp);
			}

			if (action.equals("reschduleTask")) {
				reschduleTask(req, resp);
			}

			if (action.equals("viewLog")) {
				viewLog(req, resp);
			}

			if (action.equals("taobaouser")) {
				taobaouser(req, resp);
			}

			// if (!DBConnectionMgr.getInstance().isInit()) {
			// initDB(req);
			// }
		} catch (Exception e) {
			e.printStackTrace();
			writeResponse(req, resp, null, e.getMessage());
		}
	}

	/**
	 * 初始化百会Session
	 * 
	 * @param session
	 */
	private BaihuiSession initBaihuiSession(
			TaoBaoSessionInfo taoBaoSessionInfo) throws Exception {
		BaihuiSession baihuiSession;

		baihuiSession = new BaihuiSession();
		baihuiSession.setApiKey(taoBaoSessionInfo.getCrmApiKey());
		baihuiSession.setPassword(DES.decodePw(taoBaoSessionInfo
				.getParentbaihuipw()));
		baihuiSession.setUserName(taoBaoSessionInfo.getParentbaihuiuserid());
		TicketMgr ticketMgr = new TicketMgr();
		baihuiSession.setToken(taoBaoSessionInfo.getCrmApiKey());

		return baihuiSession;
	}

	/**
	 * 初始化DB
	 */
	// private void initDB(HttpServletRequest req) throws Exception {
	// String dbconfig = this.getInitParameter(AppConstants.DBCONFIG);
	// String file = req.getRealPath(dbconfig);
	// DBConnectionMgr.getInstance().init(file);
	// }

	/**
	 * 查看导入数据的进度
	 * 
	 * @param req
	 * @param resp
	 */
	private void viewprogress(HttpServletRequest req, HttpServletResponse resp) {

	}

	/**
	 * 查看类目前导入进度
	 * 
	 * @throws Exception
	 */
	private void viewItemCatImportProgress(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			if (sessionInfo.getItemCatImportProgress() < -1) {
				writeResponse(req, resp, null,
						String.valueOf(sessionInfo.getItemCatImportProgress()));
			} else {
				writeResponse(req, resp,
						String.valueOf(sessionInfo.getItemCatImportProgress()),
						null);
			}

			sessionInfo.setValid(true);
		}
	}

	/**
	 * 查看产品导入进度
	 * 
	 * @throws Exception
	 */
	private void viewProductImportProgress(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			if (sessionInfo.getProductImportProgress() < -1) {
				writeResponse(req, resp, null,
						String.valueOf(sessionInfo.getProductImportProgress()));
			} else {
				writeResponse(req, resp,
						String.valueOf(sessionInfo.getProductImportProgress()),
						null);
			}

			sessionInfo.setValid(true);
		}
	}

	/**
	 * 查看订单导入进度
	 * 
	 * @throws Exception
	 */
	private void viewOrderImportProgress(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {

			if (sessionInfo.getOrderImportProgress() < -1) {
				writeResponse(req, resp, null,
						String.valueOf(sessionInfo.getOrderImportProgress()));
			} else {
				writeResponse(req, resp,
						String.valueOf(sessionInfo.getOrderImportProgress()),
						null);
			}

			sessionInfo.setValid(true);
		}
	}

	private void updatePassword(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String baihuiuser = req.getParameter("parentbaihuiId");
		String parentbaihuipw = req.getParameter("parentbaihuipw");
		String appName = req.getParameter("appName");
		if (appName == null || "".equals(appName)) {
			appName = "taobaocrm";
		}
		baihuiuser = URLDecoder.decode(URLDecoder.decode(baihuiuser, "utf-8"),
				"utf-8");

		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的百会用户为空!");
			return;
		}
		if (parentbaihuipw == null || parentbaihuipw.equals("")) {
			writeResponse(req, resp, null, "传递的密码用户为空!");
			return;
		}

		TPSessionDAO tpSessionDAO = new TPSessionDAO();
		Map parent = tpSessionDAO
				.findObject("select nick,sub_visitor_nick from topsession where baihuiuser='"
						+ baihuiuser + "' and appName = '" + appName + "'");
		if (parent != null && parent.get("sub_visitor_nick") != null) {
			String updateSql = "update topsession set subpw=? where sub_visitor_nick = ?";
			tpSessionDAO.updateAndInsert(updateSql, new Object[] {
					parentbaihuipw, parent.get("sub_visitor_nick") });
		} else {
			String updateSql = "update topsession set parentbaihuipw=? where nick = ?";
			tpSessionDAO.updateAndInsert(updateSql, new Object[] {
					parentbaihuipw, parent.get("nick") });
		}
		// 更改taobaouser表中的baihui密码
		String updateSql = "update taobaouser set baihuipw=? where baihuiuser = ?";
		tpSessionDAO.updateAndInsert(updateSql, new Object[] { parentbaihuipw,
				baihuiuser });

	}

	/**
	 * 根据百会账户的取出它父帐号的状态
	 * 
	 * @param baihuiid
	 */
	private int getParentStatus(String baihuiid) throws Exception {
		int status = 0;
		TPSessionDAO tpSessionDAO = new TPSessionDAO();
		Map parent = tpSessionDAO
				.findObject("select nick,sub_visitor_nick,status from topsession where sub_visitor_nick='"
						+ baihuiid + "' and appName = 'taobaocrm' ");
		// 取出父的狀態
		Map objparent = tpSessionDAO
				.findObject("select status from topsession where sub_visitor_nick is null and nick='"
						+ parent.get("nick") + "' and appName = 'taobaocrm' ");
		status = Integer.parseInt(String.valueOf(objparent.get("status")));
		return status;
	}

	/**
	 * 淘宝账户与百会账户的关联
	 * 
	 * @param req
	 * @param resp
	 */
	private void association(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		String taobaouser = req.getParameter(AppConstants.TAOBAONICK);
		String password = req.getParameter("baihuipw");
		// 解密之后的密码
		TicketMgr ticketMgr = new TicketMgr();
		String paString = DES.decodePw(password);
		String token = ticketMgr.getToken(baihuiuser, paString);
		if (token.contains("RESULT=FALSE")) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "获得token时出错,信息为：" + token);
			return;
		}
		String appName = req.getParameter("appName");
		if (appName == null || "".equals(appName)) {
			appName = "taobaocrm";
		}
		String email = req.getParameter("baihuimail");
		taobaouser = URLDecoder.decode(URLDecoder.decode(taobaouser, "utf-8"),
				"utf-8");
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的百会用户为空!");
			return;
		}
		if (taobaouser == null || taobaouser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		TPSessionDAO userDAO = new TPSessionDAO();
		boolean exist = userDAO
				.isExist("select * from topsession where ((nick = '"
						+ taobaouser + "') or (sub_visitor_nick='" + taobaouser
						+ "')) and appName = '" + appName + "' ");
		// 是否存在记录
		if (exist) {
			Map<String, Object> sub = userDAO
					.findObject("select * from topsession where  (sub_visitor_nick='"
							+ taobaouser
							+ "') and appName = '"
							+ appName
							+ "' ");
			// 是否属于子账户
			if (sub != null && sub.size() > 0) {
				// 更新子账户的baihuiuserid
				userDAO.updateAndInsert(
						"update topsession set baihuimail=?,subpw=?,crmapikey=?,baihuiuser = '"
								+ baihuiuser + "' where sub_visitor_nick='"
								+ taobaouser + "' ", new Object[] { email,
								password, token });
				// 更新子账户对应的parentbaihuipw字段
				Map<String, Object> parent = userDAO
						.findObject("select parentbaihuipw from topsession where sub_visitor_nick is null and nick = '"
								+ sub.get("nick")
								+ "' and appName = '"
								+ appName + "' ");
				if (parent.get("parentbaihuipw") != null) {
					userDAO.updateAndInsert(
							"update topsession set parentbaihuipw = ?  where baihuiuser = ?",
							new Object[] { parent.get("parentbaihuipw"),
									baihuiuser });
				}
			} else {
				// 如果是主账户，密码必须传递
				if (password == null || password.equals("")) {
					writeResponse(req, resp, null, "主账户的密码不能为空!");
					return;
				} else {
					// 更新主账户的密码
					userDAO.updateAndInsert(
							"update topsession set baihuimail=?,parentbaihuipw=?,subpw=?,crmapikey=?,baihuiuser = '"
									+ baihuiuser + "' where nick='"
									+ taobaouser + "' ", new Object[] { email,
									password, password, token });
				}
			}
		} else {
			writeResponse(req, resp, null, "百会用户" + baihuiuser + "对应的淘宝用户"
					+ taobaouser + "没有授权使用百会应用，无法进行关联，请先登录淘宝进行授权！");
		}
	}

	/**
	 * 保存从其它百会产品注册来的用户信息(crm,报表除外)
	 * 
	 * @param req
	 * @param resp
	 */
	private void taobaouser(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		String taobaouser = req.getParameter(AppConstants.TAOBAONICK);
		String password = req.getParameter("baihuipw");
		String email = req.getParameter("baihuimail");
		taobaouser = URLDecoder.decode(URLDecoder.decode(taobaouser, "utf-8"),
				"utf-8");
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的百会用户为空!");
			return;
		}
		if (taobaouser == null || taobaouser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}
		String registerSql = "";
		CommonDAO commonDAO = new CommonDAO();
		String sql = "select * from taobaouser where nick = '" + taobaouser
				+ "'";
		boolean isexit = commonDAO.isExist(sql);
		if (isexit) {
			registerSql = "update taobaouser set baihuimail = ?, baihuipw = ? where baihuiuser = ?";
			commonDAO.updateAndInsert(registerSql, new Object[] { email,
					password, baihuiuser });
		} else {
			registerSql = "insert into taobaouser(nick,baihuiuser,baihuimail,baihuipw,date) values(?,?,?,?,?)";
			commonDAO.updateAndInsert(registerSql, new Object[] { taobaouser,
					baihuiuser, email, password, new Date() });
		}
	}

	/**
	 * 导入类目数据的处理
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void importItemCatData(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		final String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			sessionInfo.setValid(true);

			if (sessionInfo.getItemCatImportProgress() >= 0
					&& sessionInfo.getItemCatImportProgress() < 100) {
				MDC.put("userid", baihuiuser);
				MDC.put("type", "商品类目");
				logger.info("商品类目数据正在同步中，请稍候...");
				return;
			}

			final HttpServletRequest request = req;
			final HttpServletResponse response = resp;
			final TaoBaoSessionInfo tbSessionInfo = sessionInfo;
			Thread thread = new Thread(new Runnable() {
				public void run() {
					try {
						// Session有效后处理业务.
						ImportItemCatDataCase itemCatDataCase = new ImportItemCatDataCase(
								tbSessionInfo);
						itemCatDataCase.importItemCatFromTaobao();
						tbSessionInfo.setItemCatImportProgress(100);
						MDC.put("userid", baihuiuser);
						MDC.put("type", "商品类目");
						logger.info("商品类目数据同步成功!");
					} catch (Exception exception) {
						tbSessionInfo.setItemCatImportProgress(-2);
						MDC.put("userid", baihuiuser);
						MDC.put("type", "商品类目");
						logger.error("商品类目数据同步失败，原因:"
								+ exception.getMessage().replace("'", "") + "!");
						writeResponse(request, response, null, exception
								.getStackTrace().toString());
					}
				}
			});

			thread.start();

			MDC.put("userid", baihuiuser);
			MDC.put("type", "商品类目");
			logger.info("商品类目数据同步任务开始!");
			writeResponse(req, resp, "商品类目数据同步任务开始!", null);
		}
	}

	/**
	 * 导入产品数据的处理
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void importProductData(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		final String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
			return;
		} else {
			if (sessionInfo.getProductImportProgress() >= 0
					&& sessionInfo.getProductImportProgress() < 100) {
				MDC.put("userid", baihuiuser);
				MDC.put("type", "商品");
				writeResponse(req, resp, null, "商品数据正在同步中，请稍候...");
				return;
			}

			final HttpServletRequest request = req;
			final HttpServletResponse response = resp;
			final HttpSession session = req.getSession();
			final TaoBaoSessionInfo tbSessionInfo = sessionInfo;
			Thread thread = new Thread(new Runnable() {
				public void run() {
					logger.info(baihuiuser + "开始同步商品");
					// try {
					long start = System.currentTimeMillis();
					// Session有效后处理业务.
					ImportProductDataCase importProductDataCase = new ImportProductDataCase(
							tbSessionInfo);
					try {
						tbSessionInfo.setProductImportProgress(2);
						importProductDataCase.importItemFromTaobao();
					} catch (Exception e) {
						logger.error(
								"商品同步从淘宝取数据时异常，原因:" + e.getMessage() + "!", e);
						ImportProductDataCase importProductDataCase1 = new ImportProductDataCase(
								tbSessionInfo);
						try {
							importProductDataCase1.importItemFromTaobao();
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							tbSessionInfo.setProductImportProgress(-2);
							return;
						}
					}
					// long taobaoend = System.currentTimeMillis();
					// logger.info("从淘宝上取商品数据用时" + (taobaoend - start)
					// + "豪秒");
					try {
						BaihuiSession baihuiSession = initBaihuiSession(
								tbSessionInfo);
						ExportProduct exportOrder = new ExportProduct(
								baihuiSession, tbSessionInfo);
						exportOrder.exportProduct(new Long(tbSessionInfo
								.getVisitor_id()));
						List<Map> exportData = new ArrayList<Map>();
						exportData = exportOrder.findExportData(
								exportOrder.Products,
								new Long(tbSessionInfo.getVisitor_id()));
						while (exportData != null) {
							try {
								exportOrder.exportProduct(new Long(
										tbSessionInfo.getVisitor_id()));

								exportData = exportOrder.findExportData(
										exportOrder.Products, new Long(
												tbSessionInfo.getVisitor_id()));
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

					} catch (Exception e) {
						logger.error("商品同步往百会写数据时异常，原因:"
								+ e.getMessage().replace("'", "") + "!", e);
					}
					// long baihuiend = System.currentTimeMillis();
					// logger.info("往百会上提交数据用时" + (baihuiend - taobaoend)
					// + "豪秒");
					tbSessionInfo.setProductImportProgress(100);

					MDC.put("userid", baihuiuser);
					MDC.put("type", "商品");
					long end = System.currentTimeMillis();
					logger.info("商品数据同步成功!共用时" + (end - start) + "毫秒");
					// } catch (Exception ex) {
					// tbSessionInfo.setProductImportProgress(-2);
					// MDC.put("userid", baihuiuser);
					// MDC.put("type", "商品");
					// logger.error(
					// "商品数据同步失败，原因:"
					// + ex.getMessage().replace("'", "")
					// + "!", ex);
					//
					// }
				}
			});

			thread.start();

			MDC.put("userid", baihuiuser);
			MDC.put("type", "商品");

			// logger.info("商品数据同步任务开始!");
			// writeResponse(req, resp, "商品数据同步任务开始!", null);
		}

	}

	/**
	 * 导入订单的处理
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void importOrderData(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		final String baihuiuser = req.getParameter(AppConstants.USERID);
		final String threeMonthData = req.getParameter("threeMonthData");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = null;
		// TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
		// .getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);

		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");

		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);

			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}

		final HttpServletRequest request = req;
		final HttpServletResponse response = resp;
		final HttpSession session = req.getSession();
		final TaoBaoSessionInfo tbSessionInfo = sessionInfo;

		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			sessionInfo.setValid(true);

			// 如果商品正在导入过程中，忽略订单的导入
			if (tbSessionInfo.getProductImportProgress() > 1
					&& tbSessionInfo.getProductImportProgress() < 100) {
				writeResponse(req, resp, null, "正在导入商品，请稍后再导入订单.");
				return;
			}

			Thread thread = new Thread(new Runnable() {
				public void run() {
					try {
						logger.info(baihuiuser + "开始同步定单");
						// 导入数据.
						// ImportData importData = new
						// ImportData(tbSessionInfo);
						tbSessionInfo.setOrderImportProgress(2);
						OrderCase orderCase = new OrderCase(tbSessionInfo);
						// 增量订单同步处理
						Date lastSyneTime = tbSessionInfo.getLastSyncTime();
						// 如果不是同步三个月的数据
						if(!"1".equals(threeMonthData)){
							// 为试用用户设置一个同步时间
							if (lastSyneTime == null) {
								Date end = new Date();
								Date start = addDays(end, -7); // 最近7天的订单
								lastSyneTime = start;
								tbSessionInfo.setLastSyncTime(lastSyneTime);
							}
							orderCase.IncrementSoldTrades(tbSessionInfo);
						}else{
							orderCase.getLast3MonthSoldTrades(tbSessionInfo);
						}

						// 从中间库中导出数据到crm中
						exportDateToBaihui(session, tbSessionInfo);

						tbSessionInfo.setOrderImportProgress(100);
						MDC.put("userid", baihuiuser);
						MDC.put("type", "订单");
					} catch (Exception ex) {
						tbSessionInfo.setOrderImportProgress(-2);
						MDC.put("userid", baihuiuser);
						MDC.put("type", "订单");
						if (ex instanceof BaihuiException) {
							return;
						}
						logger.error("订单数据同步失败，原因:" + ex.getMessage() + "!", ex);
					}
				}
			});

			thread.start();
			MDC.put("userid", baihuiuser);
			MDC.put("type", "订单");
		}
	}

	public Date addDays(Date date, int amount) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, amount);
		return c.getTime();
	}

	private void exportDateToBaihui(final HttpSession session,
			final TaoBaoSessionInfo tbSessionInfo) throws Exception,
			InterruptedException {
		CommonDAO commonDAO = new CommonDAO();
		long start = System.currentTimeMillis();
		// 将没有商品的订单export更新为-1
		updateStatusOfNoProducts(commonDAO, tbSessionInfo);
		long end = System.currentTimeMillis();
		// 导出成交用户信息
		BaihuiSession baihuiSession = initBaihuiSession(tbSessionInfo);
		ExportContacts exportContacts = new ExportContacts(baihuiSession,
				tbSessionInfo);

		List<Map> allData = exportContacts.exportDealCustomer(new Long(
				tbSessionInfo.getVisitor_id()));

		// 导出订单信息
		start = System.currentTimeMillis();
		ExportOrder exportOrder = new ExportOrder(baihuiSession, tbSessionInfo);
		exportOrder.exportOrder(new Long(tbSessionInfo.getVisitor_id()));

	}

	/**
	 * 更新商品已经下架的订单状态为-1
	 * 
	 * @param lot
	 * @param commonDAO
	 * @param tbSessionInfo
	 * @throws Exception
	 */
	private void updateStatusOfNoProducts(CommonDAO commonDAO,
			TaoBaoSessionInfo tbSessionInfo) throws Exception {
		// 查找当前批次可能下架的商品ID
		String sql = "update tborder set exported=-1 where "
				+ " (exported = 0 or exported is null) and userid= ?"
				+ " and numIid not in (select num_iid from titem where userid= ? )";
		commonDAO.updateAndInsert(
				sql,
				new Object[] { tbSessionInfo.getVisitor_id(),
						tbSessionInfo.getVisitor_id() });

	}

	/**
	 * 启动调度任务
	 */
	private void startSchedulerTask(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		// DBConnectionMgr.getInstance().init(this.getInitParameter("Dbconfig"));

		// 獲取所有關聯用戶記錄
		Connection cn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			cn = DBConnectionMgr.getConnection();
			cn.setAutoCommit(false);
			// 取得目前导入交易的最大时间，将哪个时间作为开始时间
			String sql = "select ts.baihuiuser,ts.nick,tt.*,tj.* from topsession ts,ttriggle tt,tjob tj where ts.baihuiuser=tt.userid and tt.jobid=tj.jobid";
			ps = cn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				String userID = rs.getString("userid");
				String userNick = rs.getString("nick");
				int jobType = rs.getInt("jobid");
				String triggleExp = "0/" + rs.getString("cronExp")
						+ " * * * * ?";
				String jobDesc = rs.getString("jobdescription");

				Class jobClass = null;
				switch (jobType) {
				case 1:
					jobClass = ProductImportJob.class;
					break;
				case 2:
					jobClass = OrderImportJob.class;
					break;
				case 3:
					jobClass = BuyerImportJob.class;
					break;
				case 4:
					jobClass = InvImportJob.class;
				}

				// 開始執行任務
				updateLastImportDate(userID, jobType,
						new Timestamp(System.currentTimeMillis()));

				// 开始任务执行
				startTask(userID, userNick, jobType, jobClass, triggleExp,
						jobDesc);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			releaseDBConnection(cn, ps, rs);
		}
	}

	/**
	 * 根據用戶執行對應的任務
	 * 
	 * @param userID
	 * @param jobClass
	 * @param schedulerExp
	 * @throws SchedulerException
	 */
	private void startTask(String userID, String userNick, int jobID,
			Class jobClass, String schedulerExp, String jobdesc)
			throws SchedulerException {
		System.out.println(userNick + ":" + jobdesc + " starting....");

		try {
			Scheduler scheduler = schedulerFactory.getScheduler();

			long ctime = System.currentTimeMillis();

			String jobDetailName = userID + "_" + jobClass.getName()
					+ "_jobDetail";

			JobDetail jobDetail = new JobDetail(jobDetailName,
					"jobDetailGroup", jobClass);
			String secret = "12486451be9e8540a4e6c4a58ebc4f5c842c1cdb";
			String sign = Util.md5Signature(secret);
			jobDetail.getJobDataMap().put("sign", secret);
			jobDetail.getJobDataMap().put(
					"contextPath",
					"http://localhost"
							+ this.getServletContext().getContextPath());
			jobDetail.getJobDataMap().put("userID", userID);

			String triggerName = userID + "_" + jobID + "_trigger";
			CronTrigger cronTrigger = new CronTrigger(triggerName,
					"triggerGroup");

			CronExpression cexp = new CronExpression(schedulerExp);
			cronTrigger.setCronExpression(cexp);

			scheduler.scheduleJob(jobDetail, cronTrigger);
			scheduler.start();

			// 更新最近一次抽取时间
		} catch (Exception e) {
			System.out.println(userNick + ":" + jobdesc + " 异常终止，原因如下:");
			e.printStackTrace();
		}
	}

	/*
	 * 更新最新抽取时间
	 */
	private void updateLastImportDate(String userID, long jobID,
			Timestamp lastImportDate) {
		// 獲取所有關聯用戶記錄
		Connection cn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			cn = DBConnectionMgr.getConnection();
			cn.setAutoCommit(true);
			// 取得目前导入交易的最大时间，将哪个时间作为开始时间
			String sql = "update ttriggle set lastimpdate=? where userid=? and jobid=?";
			ps = cn.prepareStatement(sql);
			ps.setTimestamp(1, lastImportDate);
			ps.setString(2, userID);
			ps.setLong(3, jobID);
			ps.execute();
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			releaseDBConnection(cn, ps, rs);
		}
	}

	/**
	 * 更新任务调度周期
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void updateSchduleTask(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			sessionInfo.setValid(true);

			String jobID = req.getParameter("jobID");
			String scheduleTime = req.getParameter("scheduleTime");
			long scheduleTimeValue = Long.parseLong(scheduleTime);

			Connection cn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				cn = DBConnectionMgr.getConnection();
				cn.setAutoCommit(true);
				String sql = "select * from ttriggle where userid='"
						+ baihuiuser + "' and jobid=" + jobID;
				ps = cn.prepareStatement(sql);
				rs = ps.executeQuery();
				if (rs.next()) {
					sql = "update ttriggle set cronExp=? where userid=? and jobid=?";
				} else {
					sql = "insert ttriggle(cronExp,userid,jobid) values(?,?,?)";
				}

				ps = cn.prepareStatement(sql);
				ps.setString(1, scheduleTime);
				ps.setString(2, baihuiuser);
				ps.setLong(3, Long.parseLong(jobID));
				ps.execute();

				// 重新开始调度

				writeResponse(req, resp, "成功更新！", null);
			} catch (Exception exception) {
				exception.printStackTrace();
			} finally {
				releaseDBConnection(cn, ps, rs);
			}
		}
	}

	/**
	 * 删除调度周期
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void deleteSchduleTask(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			sessionInfo.setValid(true);

			// 终止当前调度任务
			stopSchduleTask(req, resp);

			String jobID = req.getParameter("jobID");

			Connection cn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				cn = DBConnectionMgr.getConnection();
				cn.setAutoCommit(true);
				String sql = "delete from ttriggle where userid=? and jobid=?";

				ps = cn.prepareStatement(sql);
				ps.setString(1, baihuiuser);
				ps.setLong(2, Long.parseLong(jobID));
				ps.execute();

				// 重新开始调度
				writeResponse(req, resp, "删除成功！", null);
			} catch (Exception exception) {
				exception.printStackTrace();
			} finally {
				releaseDBConnection(cn, ps, rs);
			}
		}
	}

	/**
	 * 重新针对触发器进行调度
	 */
	private void reschduleTask(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		// 保存周期更改
		updateSchduleTask(req, resp);
		resp.reset();

		String userID = req.getParameter("USERID");
		String jobID = req.getParameter("jobID");
		String time = req.getParameter("scheduleTime");
		long timeValue = Long.parseLong(time);

		String triggerName = userID + "_" + jobID + "_trigger";
		Scheduler scheduler = schedulerFactory.getScheduler();
		SimpleTrigger trigger = (SimpleTrigger) scheduler.getTrigger(
				triggerName, "triggerGroup");
		if (trigger == null) {

			Class jobClass = null;
			int jobType = Integer.parseInt(jobID);
			switch (jobType) {
			case 1:
				jobClass = ProductImportJob.class;
				break;
			case 2:
				jobClass = OrderImportJob.class;
				break;
			case 3:
				jobClass = BuyerImportJob.class;
				break;
			case 4:
				jobClass = InvImportJob.class;
			}

			String jobDetailName = userID + "_" + jobClass.getName()
					+ "_jobDetail";
			JobDetail jobDetail = new JobDetail(jobDetailName,
					"jobDetailGroup", jobClass);
			String sign = req.getParameter(AppConstants.BAIHUISIGN);
			jobDetail.getJobDataMap().put("sign", sign);
			jobDetail.getJobDataMap().put(
					"contextPath",
					"http://localhost"
							+ this.getServletContext().getContextPath());
			jobDetail.getJobDataMap().put("userID", userID);

			// trigger = new CronTrigger(triggerName, "triggerGroup");
			// trigger.setCronExpression("0/" + time + " * * * * ?");

			trigger = new SimpleTrigger(triggerName, "triggerGroup",
					SimpleTrigger.REPEAT_INDEFINITELY, 1000 * timeValue * 60);

			Scheduler newScheduler = new StdSchedulerFactory().getScheduler();
			newScheduler.scheduleJob(jobDetail, trigger);
			newScheduler.start();
		} else {
			trigger.setRepeatInterval(1000 * timeValue * 60);
			scheduler.rescheduleJob(triggerName, "triggerGroup", trigger);
		}
	}

	/**
	 * 停止调度
	 */
	private void stopSchduleTask(HttpServletRequest req,
			HttpServletResponse resp) throws Exception {

		String userID = req.getParameter("USERID");
		String jobID = req.getParameter("jobID");

		String triggerName = userID + "_" + jobID + "_trigger";
		Scheduler scheduler = schedulerFactory.getScheduler();
		SimpleTrigger trigger = (SimpleTrigger) scheduler.getTrigger(
				triggerName, "triggerGroup");
		if (trigger != null) {
			scheduler.rescheduleJob(triggerName, "triggerGroup", trigger);
			scheduler.pauseTrigger(triggerName, "triggerGroup");
			scheduler.unscheduleJob(triggerName, "triggerGroup");
			scheduler.deleteJob(trigger.getJobName(), trigger.getJobGroup());
		}
	}

	/**
	 * 查看日志
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void viewLog(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String baihuiuser = req.getParameter(AppConstants.USERID);
		if (baihuiuser == null || baihuiuser.equals("")) {
			writeResponse(req, resp, null, "传递的淘宝用户为空!");
			return;
		}

		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 授权用户；验证用户
		TaoBaoSessionInfo sessionInfo = (TaoBaoSessionInfo) req.getSession()
				.getAttribute(baihuiuser + AppConstants.DBTOPSESSIONINFO);
		if (sessionInfo == null || sessionInfo.getParentbaihuiuserid() == null
				|| sessionInfo.getParentbaihuipw() == null) {
			// 从数据库中获取相关的SessionInfo
			sessionInfo = getSessionFromDB(req, resp, appKey, appSecretValue,
					baihuiuser);
			// 如果Session依旧不存在，则判断是否已经回调回来.
			if (sessionInfo == null) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的淘宝用户没有授权使用百会应用或者淘宝用户还没有与百会应用做关联，请修改！");
				return;
			}
			if (sessionInfo.getCrmApiKey() == null
					|| sessionInfo.getCrmApiKey().equals("")) {
				writeResponse(req, resp, null, "百会用户" + baihuiuser
						+ "对应的CRMAPIKEY为空，请修改！");
				return;
			}
			req.getSession().setAttribute(
					baihuiuser + AppConstants.DBTOPSESSIONINFO, sessionInfo);
		}
		// 如果sessionInfo存在，则判断session对应的用户是否有效
		if (sessionInfo.getSub_visitor_nick() == null
				&& !isSessionValid(sessionInfo.getTopParameter().getTs(),
						sessionInfo.getTopParameter().getExpires_in())) {
			writeResponse(req, resp, null, "百会用户" + baihuiuser
					+ "对应的淘宝用户授权信息已经过期，请登录淘宝进行重新授权！");
		} else {
			sessionInfo.setValid(true);

			String startTime = req.getParameter("startTime");
			String endTime = req.getParameter("endTime");

			Connection cn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				JSONObject jsonObject = new JSONObject();
				cn = DBConnectionMgr.getConnection();
				cn.setAutoCommit(true);

				String sql = "select * from tlog where userid='" + baihuiuser
						+ "'";

				if (startTime != null && startTime.length() > 0) {
					sql = sql + " and logdate>='" + startTime + "'";
				}

				if (endTime != null && endTime.length() > 0) {
					sql = sql + " and logdate<='" + endTime + "'";
				}

				ps = cn.prepareStatement(sql);
				rs = ps.executeQuery();
				int nIndex = 0;
				while (rs.next()) {
					nIndex++;
					JSONObject rowJsonObject = new JSONObject();
					rowJsonObject.put("userid", rs.getString("userid"));
					rowJsonObject.put("type", rs.getString("type"));
					rowJsonObject.put("content", rs.getString("content"));
					rowJsonObject.put("logdate",
							rs.getTimestamp("logdate") == null ? "" : rs
									.getTimestamp("logdate").toString());

					jsonObject.put(nIndex, rowJsonObject);
				}

				// 重新开始调度
				writeResponse(req, resp, jsonObject);
			} catch (Exception exception) {
				exception.printStackTrace();
			} finally {
				releaseDBConnection(cn, ps, rs);
			}
		}

	}

	/**
	 * 释放数据库连接
	 */
	private void releaseDBConnection(Connection cn, PreparedStatement ps,
			ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (cn != null)
				cn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 处理授权问题
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	private void initAuthorize(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		// 从servlet参数中获取appKey和appSecretValue
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		// 是否是回调回来的
		String topSession = req.getParameter(AppConstants.TOPSESSIONNAME);
		if (topSession != null) {
			handleTaobaoAuthorize(req, resp, appKey, appSecretValue, topSession);
		} else {
			redirectToAuthorize(resp, appKey);
		}
	}

	/**
	 * 处理淘宝请求.
	 * 
	 * @param req
	 * @param resp
	 * @param appKey
	 * @param appSecretValue
	 * @param topSession
	 * @throws Exception
	 */
	private void handleTaobaoAuthorize(HttpServletRequest req,
			HttpServletResponse resp, String appKey, String appSecretValue,
			String topSession) throws Exception {
		// 授权成功后获取appKey,appParam,topSession.授权成功后Tabobao会返回一个回调地址。
		String appParams = req.getParameter(AppConstants.APPPARAMETERNAME);
		String topSign = req.getParameter(AppConstants.TOPSIGN);
		CommonDAO comDao = new CommonDAO();
		// 0:子帐号，1：父帐号
		int isParent = 0;
		// 校验回调url的正确性
		TaoBaoCallBackUrlMgt parse = new TaoBaoCallBackUrlMgt(appKey,
				appParams, topSession, topSign, appSecretValue);
		if (parse.verify()) {
			// 存储值在Session中
			TaoBaoSessionInfo taoBaoSessionInfo = parse.getTaoBaoSessionInfo();
			taoBaoSessionInfo.setValid(true);
			// req.getSession().setAttribute(AppConstants.TOPSESSIONINFO,
			// taoBaoSessionInfo);
			// 同步用户到本地库中
			TPSessionDAO userDAO = new TPSessionDAO();
			UserCase aCase = new UserCase(taoBaoSessionInfo);
			String nick = null;
			if (taoBaoSessionInfo.getTopParameter().getSub_visitor_nick() != null) {
				nick = taoBaoSessionInfo.getTopParameter()
						.getSub_visitor_nick();
				User mainUser = aCase.getUserInfo(taoBaoSessionInfo);
				if (mainUser != null) {
					taoBaoSessionInfo.setVisitor_nick(mainUser.getNick());
				}
			} else {
				isParent = 1;
				nick = taoBaoSessionInfo.getTopParameter().getVisitor_nick();
			}
			User userInfo = aCase.getUserInfo(nick);
			// boolean insert = false;
			// initDB(req);

			boolean exist = false;
			int status = 0;

			Map<String, Object> map = userDAO
					.findObject("select * from topsession where ((nick = '"
							+ nick + "') or (sub_visitor_nick='" + nick
							+ "')) and appName = 'taobaocrm' ");
			if (!map.isEmpty()) {
				if (map.get("sub_visitor_nick") == null
						|| "".equals(map.get("sub_visitor_nick").toString())) {
					status = Integer
							.parseInt(String.valueOf(map.get("status")));
				} else {
					// 找出父的状态
					status = getParentStatus(String.valueOf(map
							.get("sub_visitor_nick")));
				}
				exist = true;
			}
			if (!exist) {
				// 如果用户不存在，则同步,否则更新一些字段
				userDAO.insert(userInfo, taoBaoSessionInfo);
				Map taobaouserMap = comDao.find(nick, "nick", "taobaouser");

				// 主帐号
				if (isParent == 1) {
					if (!taobaouserMap.isEmpty()) {
						userDAO.updateAndInsert(
								"update topsession set baihuimail=?,parentbaihuipw=?,subpw=?,baihuiuser =? where nick=?",
								new Object[] { taobaouserMap.get("baihuimail"),
										taobaouserMap.get("baihuipw"),
										taobaouserMap.get("baihuipw"),
										taobaouserMap.get("baihuiuser"),
										taobaouserMap.get("nick") });
					}
				} else if (isParent == 0) {
					status = getParentStatus(nick);
					if (!taobaouserMap.isEmpty()) {
						userDAO.updateAndInsert(
								"update topsession set baihuimail=?,parentbaihuipw=?,subpw=?,baihuiuser =? where sub_visitor_nick=?",
								new Object[] { taobaouserMap.get("baihuimail"),
										taobaouserMap.get("baihuipw"),
										taobaouserMap.get("baihuipw"),
										taobaouserMap.get("baihuiuser"),
										taobaouserMap.get("nick") });
					}
				}

				// 更新子账户对应的parentbaihuipw字段
				Map<String, Object> parent = userDAO
						.findObject("select parentbaihuipw from topsession where sub_visitor_nick is null and nick = '"
								+ nick + "' and appName = 'taobaocrm' ");
				if (parent.get("parentbaihuipw") != null) {
					userDAO.updateAndInsert(
							"update topsession set parentbaihuipw = ?  where baihuiuser = ?",
							new Object[] { parent.get("parentbaihuipw"),
									taobaouserMap.get("baihuiuser") });
				}

			} else {
				userDAO.update(userInfo, taoBaoSessionInfo);
			}
			// // 如果已经做了关联，将百会用户传递给百会，百会可能会做单点登录
			// <<<<<<< .mine
			// String baihuiuser = null;
			// // if (!insert) {
			// Map dataUser = userDAO.find(userInfo.getUserId(), "user_id",
			// "topsession");
			// baihuiuser = (String) dataUser.get("baihuiuser");
			// if (baihuiuser == null) {
			// baihuiuser = "";
			// }
			// =======
			String baihuiuser = null;

			Map<String, Object> dataUser = userDAO
					.findObject("select baihuiuser from topsession where user_id = "
							+ userInfo.getUserId()
							+ " and (baihuiuser is not null  and baihuiuser != '') limit 1");
			baihuiuser = (String) dataUser.get("baihuiuser");
			if (baihuiuser == null) {
				baihuiuser = "";
			}
			// >>>>>>> .r336
			// }
			resp.sendRedirect(this.getInitParameter("BAIHUIINDEX")
					+ "?TBNick="
					+ URLEncoder.encode(URLEncoder.encode(nick, "utf-8"),
							"utf-8")
					+ "&appName=taobaocrm&action=init&encode=utf-8&status="
					+ status + "&isParent=" + isParent + "&baihuiuser="
					+ baihuiuser);
		} else {
			resp.sendRedirect(resp
					.encodeURL("error.jsp?msg='The callback parameter is invalid.'"));
		}
	}

	/**
	 * 通过appKey+appSecretValue加了MD5加密之后校验
	 * 
	 * @param req
	 * @param resp
	 * @return
	 */
	private boolean validateSecurity(HttpServletRequest req,
			HttpServletResponse resp, String action) {
		// 初始化授权时不判断安全性
		if ("init".equals(action)) {
			return true;
		}
		String appKey = this.getInitParameter("APPKEY");
		String appSecretValue = this.getInitParameter("APPSecretVALUE");
		String sign = req.getParameter(AppConstants.BAIHUISIGN);
		if (sign == null || sign.equals(""))
			return false;
		return sign.equals(Util.md5Signature(appKey + appSecretValue));
	}

	/**
	 * 从数据库中获取Session等信息
	 * 
	 * @param req
	 * @param resp
	 * @param appKey
	 * @param appSecretValue
	 * @return
	 * @throws Exception
	 */
	private TaoBaoSessionInfo getSessionFromDB(HttpServletRequest req,
			HttpServletResponse resp, String appKey, String appSecretValue,
			String baihuiuser) throws Exception {
		// 从数据库中查找用户信息
		TPSessionDAO userDAO = new TPSessionDAO();
		// 根据百会应用对应的ID来查找数据
		Map userInfo = userDAO
				.findObject("select * from topsession where baihuiuser = '"
						+ baihuiuser + "' and appName = 'taobaocrm'");

		if (userInfo == null || userInfo.size() <= 0)
			return null;
		String token = "";
		if(userInfo.get("crmapikey") == null || "".equals(userInfo.get("crmapikey"))){
			// 解密之后的密码
			TicketMgr ticketMgr = new TicketMgr();
			String paString = DES.decodePw(String.valueOf(userInfo.get("parentbaihuipw")));
			token = ticketMgr.getToken(baihuiuser, paString);
			
			userDAO.updateAndInsert(
					"update topsession set crmapikey=? where baihuiuser = ? ", new Object[] {
							token, baihuiuser });
		}

		// 如果session信息不存在，则必须重新授权
		String topSession = (String) userInfo.get("sessionid");
		if (topSession == null)
			return null;
		// 构造topParam信息
		TopParameter parameter = new TopParameter();
		if (userInfo.get("expires_in") != null)
			parameter.setExpires_in((Long) userInfo.get("expires_in"));
		if (userInfo.get("iframe") != null)
			parameter.setIframe((String) userInfo.get("iframe"));
		if (userInfo.get("re_expires_in") != null)
			parameter.setRe_expires_in((Long) userInfo.get("re_expires_in"));
		if (userInfo.get("sub_visitor_id") != null)
			parameter.setSub_visitor_id(((Integer) userInfo
					.get("sub_visitor_id")));
		if (userInfo.get("sub_visitor_nick") != null)
			parameter.setSub_visitor_nick((String) userInfo
					.get("sub_visitor_nick"));
		if (userInfo.get("ts") != null)
			parameter.setTs((Long) userInfo.get("ts"));

		if (userInfo.get("user_id") != null)
			parameter.setVisitor_id((Integer) userInfo.get("user_id"));
		if (userInfo.get("nick") != null)
			parameter.setVisitor_nick((String) userInfo.get("nick"));
		// 如果是父账户，则直接通过，否则需要查找父亲账户
		String parentPwd = userInfo.get("parentbaihuipw") == null ? null
				: (String) userInfo.get("parentbaihuipw");
		String baihuiuserid = baihuiuser;
		String crmApiKey = ((userInfo.get("crmapikey") == null) || ("".equals(userInfo.get("crmapikey")))) ? token
				: (String) userInfo.get("crmapikey");
		// 如果是子账户
		Object tbimportMaxCount = userInfo.get("tbimportMaxCount");
		Object bhexportMaxCount = userInfo.get("bhexportMaxCount");
		if (parameter.getSub_visitor_nick() != null
				&& parameter.getSub_visitor_nick().length() > 0) {
			userInfo = userDAO
					.findObject("select * from topsession where nick = '"
							+ parameter.getVisitor_nick()
							+ "' and sub_visitor_nick is null and appName = 'taobaocrm' ");
			baihuiuserid = (String) userInfo.get("baihuiuser");
			crmApiKey = (String) userInfo.get("crmapikey");
			tbimportMaxCount = userInfo.get("tbimportMaxCount");
			bhexportMaxCount = userInfo.get("bhexportMaxCount");
		}

		TaoBaoSessionInfo sessionInfo = new TaoBaoSessionInfo(appKey,
				parameter, topSession, appSecretValue, parentPwd, baihuiuserid,
				crmApiKey);
		if (tbimportMaxCount != null && tbimportMaxCount instanceof Integer) {
			sessionInfo.setTbMaxCount(((Integer) tbimportMaxCount).intValue());
		}
		if (bhexportMaxCount != null && bhexportMaxCount instanceof Integer) {
			sessionInfo.setBhMaxCount(((Integer) bhexportMaxCount).intValue());
		}
		if (userInfo.get("lastSyncTime") != null
				&& !"".equals(userInfo.get("lastSyncTime"))) {
			sessionInfo.setLastSyncTime(convertDate(String.valueOf(userInfo
					.get("lastSyncTime"))));
		} else {
			sessionInfo.setLastSyncTime(null);
		}
		return sessionInfo;
	}

	public static Date convertDate(String adateStrteStr) {
		java.util.Date date = null;
		try {

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			date = simpleDateFormat.parse(adateStrteStr);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return date;
	}

	/**
	 * 自动导向授权页面
	 * 
	 * @param resp
	 * @param appKey
	 * @throws IOException
	 */
	private void redirectToAuthorize(HttpServletResponse resp, String appKey)
			throws IOException {
		String redirectUrl = AppConstants.TAOBAOONLINECONTAINERURL + "?appkey="
		// + appKey + "&encode=utf-8";
				+ appKey;
		resp.sendRedirect(redirectUrl);
	}

	// 如何判断Session是否有效
	public boolean isSessionValid(long ts, long expires_in) {
		return System.currentTimeMillis() < (ts + expires_in * 1000l);
	}

	/**
	 * 判断操作是否正确
	 * 
	 * @param action
	 * @return
	 */
	private boolean validActions(String action) {
		List l = Arrays.asList(actions);
		return l.contains(action);
	}

	/**
	 * 输出内容
	 * 
	 * @param resp
	 * @param successMsg
	 * @param errMsg
	 */
	private void writeResponse(HttpServletRequest req,
			HttpServletResponse resp, String successMsg, String errMsg) {

		JSONObject jsonObject = new JSONObject();
		if (successMsg != null && !successMsg.equals("")) {
			jsonObject.put("successMsg", successMsg);
		}
		if (errMsg != null && !errMsg.equals("")) {
			jsonObject.put("errMsg", errMsg);
			logger.error(jsonObject.toString());
		}
		writeResponse(req, resp, jsonObject);
	}

	/**
	 * 输出内容到Response中
	 * 
	 * @param resp
	 * @param jsonObject
	 */
	private void writeResponse(HttpServletRequest req,
			HttpServletResponse resp, JSONObject jsonObject) {

		resp.setCharacterEncoding("utf-8");
		// resp.setContentType("application/json");
		resp.setContentType("text/html");
		try {
			resp.getWriter().write(jsonObject.toString());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入日志
	 */
	private void writeLog(String userID, String type, String summary,
			String content) {
		// // 獲取所有關聯用戶記錄
		// Connection cn = null;
		// PreparedStatement ps = null;
		// ResultSet rs = null;
		//
		// try {
		// DBConnectionMgr.getInstance().init(
		// this.getInitParameter("Dbconfig"));
		//
		// cn = DBConnectionMgr.getInstance().getConnection();
		// cn.setAutoCommit(true);
		// // 取得目前导入交易的最大时间，将哪个时间作为开始时间
		// String sql = "insert into tlog values(?,?,?,?,?)";
		// ps = cn.prepareStatement(sql);
		//
		// ps.setObject(1, userID);
		// ps.setObject(2, new Timestamp(System.currentTimeMillis()));
		// ps.setObject(3, type);
		// ps.setObject(4, summary);
		// ps.setObject(5, content);
		//
		// ps.execute();
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// } finally {
		// releaseDBConnection(cn, ps, rs);
		// }
	}
}